package com.qywx.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @ClassName RestTemplateUtil
 * @Description: TODO
 * @Author wmj
 * @Date 2020/3/7
 * @Version V1.0
 **/
@Component
public class RestTemplateUtil {
    @Autowired
    RestTemplate restTemplate;
    @Value("${wechat.corpid}")
    private String corpid; //= "wwe87430dea0b955f2";
    @Value("${wechat.corpsecret}")
    private String corpsecret; // = "a9TuLK8YfG51enZwCVmNxfx8xPEI_AGtHBKKk7ajZIk";

    //获取access_token
    public  String getaccessToken(){
        String accessokenTUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+corpsecret;
        Map map = restTemplate.getForObject(accessokenTUrl, Map.class);
        Integer  errcode = (Integer) map.get("errcode");
        if(0==errcode){
            String accessToken = (String) map.get("access_token");
            return accessToken;
        }else {
            return null;
        }
    }

    /**
     * @MethodName: postRequest
     * @Description: post请求
     * @Param: [url：路径, entity：请求体]
     * @Return: java.util.Map
     * @Author: wmj
     * @Date: 2020/3/10
    **/
    public  Map postRequest(String url,Object entity){
        JSONObject jsonObj = (JSONObject) JSONObject.toJSON(entity);
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        //请求体
        HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(),headers);
        //发起请求
        Map resultMap = restTemplate.postForObject(url, formEntity, Map.class);
        return resultMap;
    }

    public  Map postStringRequest(String url,String str){
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("user",str);
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        //请求体
        HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(),headers);
        //发起请求
        Map resultMap = restTemplate.postForObject(url, formEntity, Map.class);
        return resultMap;
    }
}
